package cn.hzking.gjmall.activitys.order;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.hzking.gjmall.R;
import cn.hzking.gjmall.activitys.coupon.CouponListActivity;
import cn.hzking.gjmall.activitys.my.AddAdressActivity;
import cn.hzking.gjmall.activitys.my.SelectAddressActivity;
import cn.hzking.gjmall.adpters.order.SureOrderAdapter;
import cn.hzking.gjmall.app.Gjmall;
import cn.hzking.gjmall.base.ColorStatuBarActivity;
import cn.hzking.gjmall.bean.OrderIdBean;
import cn.hzking.gjmall.bean.PayBean;
import cn.hzking.gjmall.bean.PayMessageBean;
import cn.hzking.gjmall.bean.SureOrderBean;
import cn.hzking.gjmall.net.RetrofitFactory;
import cn.hzking.gjmall.net.base.BaseEntity;
import cn.hzking.gjmall.net.base.BaseObserver;
import cn.hzking.gjmall.utils.CheckInstallApp;
import cn.hzking.gjmall.utils.IdentificationCodeUtil;
import cn.hzking.gjmall.utils.Logger;
import cn.hzking.gjmall.utils.OnClickEvent;
import cn.hzking.gjmall.utils.PriceFormatUtils;
import cn.hzking.gjmall.utils.SPUtils;
import cn.hzking.gjmall.utils.UIUtils;
import cn.hzking.gjmall.view.MyListView;
import cn.hzking.gjmall.view.SimpleOptionView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 确认订单
 * item_sureorder
 * item_sure_order_gooddetail
 */
public class SureOrderActivity extends ColorStatuBarActivity {
    public static final int RESULT_DATA=100;
    @Bind(R.id.order_price)
    TextView orderPrice; //实际支付金额
    @Bind(R.id.order_pay)
    TextView orderPay; //支付订单
    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.sureorder_name)
    TextView sureorderName; //收货人姓名
    @Bind(R.id.sureorder_phonenum)
    TextView sureorderPhonenum; //收货人手机号码
    @Bind(R.id.sureorder_address)
    TextView sureorderAddress; //收货人地址
    @Bind(R.id.recyclerview_order)
    MyListView recyclerview; //列表
    @Bind(R.id.sure_order_price_o)
    TextView sureOrderPrice;//商品金额
    @Bind(R.id.sure_order_suifei_o)
    TextView sureOrderSuifei;//税费
    @Bind(R.id.sure_order_yunfei_o)
    TextView sureOrderYunfei; //运费
    @Bind(R.id.sure_order_activity_o)
    TextView sureOrderActivity;//活动优惠
    @Bind(R.id.tv_noaddress)
    TextView tvNoaddress; //没有地址
    @Bind(R.id.address_rl)
    RelativeLayout addressRl; //有地址布局
    @Bind(R.id.et_name)
    EditText etName;   //姓名输入框
    @Bind(R.id.et_cardnum)
    EditText etCardnum; //身份证号码输入框
    @Bind(R.id.know_more)
    TextView knowMore; //了解更多
    @Bind(R.id.shimin_ll)
    LinearLayout shiMinLl;//实名认证布局
    @Bind(R.id.kuajing_ll)
    LinearLayout kuangJinLl;//跨境布局
    @Bind(R.id.kuajing_select)
    ImageView imageKj;//跨境须知按钮
    @Bind(R.id.kuajin_text)
    TextView tvKj;//跨境须知文字
    @Bind(R.id.coupon_ll)
    RelativeLayout couponRl;//y优惠券布局
    @Bind(R.id.coupon__name)
    TextView tvCouponName;//优惠券名称
    private String itemSkuIds;//skuId集合
    private String numbers;//每个sku的数量
    private boolean isBond;//是否是自营保税
    private String nextSkuIds;//下一个订单的skuId;
    private String newxNumbers;//下一个订单的每个商品的个数
    private SureOrderAdapter sureOrderAdapter;
    private String addressId;
    private IWXAPI api;
    private int groupId;//支付单订单id
    private String couponId;//优惠券ID
    private String couponSkuIds;//优惠券SKUID
    private String couponName;//优惠券名称
    private String addressDOId;//addressId
    private boolean hasCrossBorder;//是否有跨境商品
    private boolean isKjSelected = true;//跨境协议是否同意
    private String kjUri;//跨境uri
    private String smUri;//实名uri
    private boolean realName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_sure_order);
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        simpleTileView.setTitle("确认订单");
        addressDOId = SPUtils.getAddressId(this);
        imageKj.setSelected(true);//选中状态
        Intent intent = getIntent();
        itemSkuIds = intent.getStringExtra("itemSkuIds");
        numbers = intent.getStringExtra("numbers");
        nextSkuIds = intent.getStringExtra("nextSkuIds");
        newxNumbers = intent.getStringExtra("nextNumbers");
        isBond = intent.getBooleanExtra("isBond", false);
        api = WXAPIFactory.createWXAPI(this, Gjmall.getWxAppId());
        initReclcerview();
        initListener();
        getNetData();

    }

    private void initReclcerview() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerview.setLayoutManager(linearLayoutManager);
        sureOrderAdapter = new SureOrderAdapter(R.layout.item_sureorder, null);
        recyclerview.setAdapter(sureOrderAdapter);
    }

    private void initListener() {
        //实名须知
        knowMore.setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                //todo 实名认证须知
            }
        });
        //优惠券
        couponRl.setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                Intent intent = new Intent(SureOrderActivity.this, CouponListActivity.class);
                intent.putExtra("skuIds",itemSkuIds);
                intent.putExtra("numbers",numbers);
                startActivityForResult(intent,RESULT_DATA);
            }
        });
        //跨境须知是否同意按钮
        imageKj.setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                if (isKjSelected) {
                    imageKj.setSelected(false);
                    isKjSelected = !isKjSelected;
                } else {
                    imageKj.setSelected(true);
                    isKjSelected = !isKjSelected;
                }

            }
        });
        //跨境须知跳转
        tvKj.setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                //todo 跨境u ri
                if (!TextUtils.isEmpty(kjUri)) {

                }

            }
        });
        //地址按钮
        addressRl.setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                Intent intent = new Intent(SureOrderActivity.this, SelectAddressActivity.class);
                startActivityForResult(intent,RESULT_DATA);
            }
        });

        //没有地址的文本按钮
        tvNoaddress.setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                Intent intent = new Intent(SureOrderActivity.this, AddAdressActivity.class);
                startActivityForResult(intent,RESULT_DATA);
            }
        });

        //支付按钮(先生成订单)
        orderPay.setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                if(TextUtils.isEmpty(sureorderAddress.getText().toString().trim())){//没有选择地址的时候
                    UIUtils.showToast(SureOrderActivity.this,"请选择收货地址",Toast.LENGTH_SHORT);
                    return;
                }
                if (hasCrossBorder) {//跨境商品
                    if (imageKj.isSelected()) {
                        if (realName) {//已经实名认证了
                            getOrderId();
                        } else {//没有实名认证
                            getRealInfo();

                        }
                    } else {
                        UIUtils.showToast(SureOrderActivity.this, "请同意跨境商品须知", Toast.LENGTH_SHORT);
                    }
                } else {
                    getOrderId();
                }


            }
        });
    }

    //获取实名信息
    private void getRealInfo() {
        String card = etCardnum.getText().toString().trim();
        String name = etName.getText().toString().trim();
        boolean identityCode = IdentificationCodeUtil.isIdentityCode(card);
        if (!TextUtils.isEmpty(name) && identityCode) {
            realName(name, card);
        }

    }

    //实名认证
    private void realName(String realname, String cardnum) {
        RetrofitFactory.getInstant().API().realName(realname, cardnum)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseEntity value) {
                        getOrderId();

                    }

                    @Override
                    public void onError(Throwable e) {
                        UIUtils.showToast(SureOrderActivity.this, "实名认证错误", Toast.LENGTH_SHORT);

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    //生成支付单
    private void getOrderId() {
        HashMap<String, String> parms = new HashMap<>();
        parms.put("itemSkuIds", itemSkuIds);
        parms.put("numbers", numbers);
        parms.put("paymethod", "WX_MP_PAY");
        parms.put("addressId", addressDOId);
        parms.put("couponId",couponId);
        if(!TextUtils.isEmpty(couponSkuIds)){
            parms.put("couponSkuIds", couponSkuIds);
        }
        RetrofitFactory.getInstant().API()
                .getOrderId(parms)
                .compose(this.<OrderIdBean>setThread())
                .subscribe(new BaseObserver<OrderIdBean>(this, true, true) {
                    @Override
                    protected void onSuccees(OrderIdBean orderIdBean) throws Exception {

                        //成功的话就请求支付的id
                        OrderIdBean.DataBean data = orderIdBean.getData();
                        if (data != null) {
                            groupId = data.getOrderPayGroups().get(0).getGroupId();
                            payWx(String.valueOf(groupId));
                        }

                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        Logger.e(e.getMessage());

                    }

                    @Override
                    protected void onCodeError(OrderIdBean orderIdBean) throws Exception {
                        super.onCodeError(orderIdBean);
                        String errorMsg = orderIdBean.getErrorMsg();
                        //错误提示对话框
                        createTishiDialog(errorMsg).show();

                    }
                });

    }

    //微信支付
    private void payWx(String orderGroupId) {
        RetrofitFactory.getInstant().API()
                .payWx(orderGroupId)
                .compose(this.<PayBean>setThread())
                .subscribe(new BaseObserver<PayBean>(this, true, true) {
                    @Override
                    protected void onSuccees(PayBean payBean) throws Exception {
                        if (payBean != null) {
                            PayBean.DataBean data = payBean.getData();
                            if (data != null) {
                                PayBean.DataBean.SignPackageBean signPackage = data.getSignPackage();
                                if (signPackage != null) {
                                    PayReq req = new PayReq();
                                    req.appId = signPackage.getAppId();
                                    req.partnerId = signPackage.getPartnerId();
                                    req.prepayId = signPackage.getPrepayid();
                                    req.packageValue = signPackage.getPackageX();
                                    req.nonceStr = signPackage.getNonceStr();
                                    req.timeStamp = signPackage.getTimeStamp();
                                    req.sign = signPackage.getPaySign();
                                    req.extData = "app data";
                                    if (CheckInstallApp.isWeixinAvilible(Gjmall.getApplicationContext())) {
                                        if (TextUtils.isEmpty(nextSkuIds)) {
                                            EventBus.getDefault().postSticky(new PayMessageBean(itemSkuIds, numbers, nextSkuIds, newxNumbers, false, String.valueOf(groupId)));
                                        } else {
                                            EventBus.getDefault().postSticky(new PayMessageBean(itemSkuIds, numbers, nextSkuIds, newxNumbers, true, String.valueOf(groupId)));
                                        }
                                        api.sendReq(req);
                                        UIUtils.showToast(SureOrderActivity.this, "正在调起支付", Toast.LENGTH_SHORT);
                                    } else {
                                        UIUtils.showToast(SureOrderActivity.this, "请安装微信", Toast.LENGTH_SHORT);
                                    }
                                }
                            }
                        }

                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {

                    }
                });

    }


    //获取确认订单页面数据网络数据
    private void getNetData() {
        HashMap<String, String> parms = new HashMap<>();
        parms.put("itemSkuIds", itemSkuIds);
        parms.put("numbers", numbers);
        if(!TextUtils.isEmpty(addressDOId)){
            parms.put("addressId", addressDOId);
        }
        if(!TextUtils.isEmpty(couponId)){
            parms.put("couponId", couponId);
        }
        if(!TextUtils.isEmpty(couponSkuIds)){
            parms.put("couponSkuIds", couponSkuIds);
        }
        RetrofitFactory.getInstant().API()
                .getSureOrderData(parms)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<SureOrderBean>(this, true, true) {
                    @Override
                    protected void onSuccees(SureOrderBean sureOrderBean) throws Exception {
                        if (sureOrderBean != null) {
                            addressId = String.valueOf(sureOrderBean.getData().getAddressId());
                            sureOrderAdapter.setNewData(sureOrderBean.getData().getItemHolders());
                            initView(sureOrderBean);
                        }

                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {

                    }
                });

    }

    //显示view
    private void initView(SureOrderBean sureOrderBean) {
        kjUri = sureOrderBean.getData().getKjUrl();
        smUri = sureOrderBean.getData().getSmUrl();
        realName = sureOrderBean.getData().isRealName();
        //是否能使用优惠券
        if (sureOrderBean.getData().getCouponSkuIdsArray() != null) {
            List<?> couponSkuIdsArray = sureOrderBean.getData().getCouponSkuIdsArray();
            if (couponSkuIdsArray.size() == 0) {
                couponRl.setVisibility(View.GONE);
            } else {
                couponRl.setVisibility(View.VISIBLE);
                if(!TextUtils.isEmpty(couponName)){
                    tvCouponName.setText(couponName);
                }else {
                    tvCouponName.setText(String.format(Locale.CHINA, "您有%d张可用优惠券", couponSkuIdsArray.size()));
                }
            }
        }
        //是否显示实名认证接口
        hasCrossBorder = false;
        for (int i = 0; i < sureOrderBean.getData().getItemHolders().size(); i++) {
            if (sureOrderBean.getData().getItemHolders().get(i).isHasCrossBorder()) {
                hasCrossBorder = true;
                break;
            }

        }
        SureOrderBean.DataBean.UserBean user = sureOrderBean.getData().getUser();
        if (user != null) {
            if (hasCrossBorder && TextUtils.isEmpty(user.getIdCardNumber())) {//需要实名信息
                shiMinLl.setVisibility(View.VISIBLE);

            } else {
                shiMinLl.setVisibility(View.GONE);
            }
        } else {
            if (hasCrossBorder) {
                shiMinLl.setVisibility(View.GONE);
            }
        }
        //跨境须知按钮
        if (hasCrossBorder) {
            kuangJinLl.setVisibility(View.VISIBLE);
        } else {
            kuangJinLl.setVisibility(View.GONE);
        }
        //设置地址
        SureOrderBean.DataBean dataBean = sureOrderBean.getData();
        if (dataBean != null) {
            SureOrderBean.DataBean.AddressDOBean addressDO = dataBean.getAddressDO();
            if (dataBean.getAddressDO() != null) {//地址对象不为空
                addressDOId = String.valueOf(addressDO.getId());
                if (TextUtils.isEmpty(addressDO.getReceiverName()) &&
                        TextUtils.isEmpty(addressDO.getLongAddress()) && TextUtils.isEmpty(addressDO.getReceiverTel())) {
                    addressRl.setVisibility(View.GONE);
                    tvNoaddress.setVisibility(View.VISIBLE);
                } else {//有收获地址
                    addressRl.setVisibility(View.VISIBLE);
                    tvNoaddress.setVisibility(View.GONE);
                    sureorderName.setText(addressDO.getReceiverName());
                    sureorderAddress.setText(addressDO.getLongAddress());
                    sureorderPhonenum.setText(addressDO.getReceiverTel());
                }
            } else {//地址对象为空
                addressRl.setVisibility(View.GONE);
                tvNoaddress.setVisibility(View.VISIBLE);
            }
        }
        double skuTotalPrice = dataBean.getSkuTotalPrice();//商品金额
        double totalFreight = dataBean.getTotalFreight();//总运费
        double totalPrice = dataBean.getTotalPrice();
        double totalTax = dataBean.getTotalTax();//总税费
        double couponReducePrice = 0;//总优惠价格
        List<SureOrderBean.DataBean.ItemHoldersBean> itemHolders = dataBean.getItemHolders();
        for (int i = 0; i < itemHolders.size(); i++) {
            List<SureOrderBean.DataBean.ItemHoldersBean.OrderItemsBean> orderItems = itemHolders.get(i).getOrderItems();
            for (int j = 0; j < orderItems.size(); j++) {
                couponReducePrice += orderItems.get(j).getCouponReducePrice();

            }
        }
        sureOrderSuifei.setText("税费: ¥" + PriceFormatUtils.valueFormatWithTwo(String.valueOf(totalTax)));
        sureOrderYunfei.setText("运费: ¥" + PriceFormatUtils.valueFormatWithTwo(String.valueOf(totalFreight)));
        sureOrderPrice.setText("商品金额: ¥" + PriceFormatUtils.valueFormatWithTwo(String.valueOf(skuTotalPrice)));
        sureOrderActivity.setText("活动优惠: ¥" + PriceFormatUtils.valueFormatWithTwo(String.valueOf(couponReducePrice)));
        orderPrice.setText("¥" + PriceFormatUtils.valueFormatWithTwo(String.valueOf(totalPrice)));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }


    public Dialog createTishiDialog(String textString) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.dialog_sureorder_tishi, null);// 得到加载view
        TextView textView = v.findViewById(R.id.sureorder_text);
        textView.setText(String.valueOf(textString));
        final Dialog customDialog = new Dialog(this, R.style.dialog_1);// 创建自定义样式dialog
        customDialog.setCanceledOnTouchOutside(true);
        customDialog.setCancelable(true);
        customDialog.setContentView(v);
        v.findViewById(R.id.sure).setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                EventBus.getDefault().post("错误返回");
                finish();


            }
        });


        return customDialog;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_DATA) {
            if(data!=null){
                addressDOId=data.getExtras().getString("addressId");
                couponName=data.getExtras().getString("couponName");
                couponId=data.getExtras().getString("couponId");
                couponSkuIds=data.getExtras().getString("couponSkuIds");
                getNetData();
            }
        }
    }

}
